package com.dounine.clouddisk360.parser;

import java.io.IOException;

import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dounine.clouddisk360.parser.deserializer.authtoken.AuthToken;
import com.dounine.clouddisk360.parser.deserializer.authtoken.AuthTokenConfig;
import com.dounine.clouddisk360.parser.deserializer.authtoken.AuthTokenConst;
import com.dounine.clouddisk360.parser.deserializer.authtoken.AuthTokenRequestInterceptor;
import com.dounine.clouddisk360.parser.deserializer.authtoken.AuthTokenResponseHandle;
import com.dounine.clouddisk360.pool.PoolingHttpClientConnection;

public class AuthTokenParser extends BaseParser<AuthTokenConfig> {

	private static final Logger LOGGER = LoggerFactory.getLogger(AuthTokenParser.class);

	@Override
	public void initConfig(AuthTokenConfig authTokenConfig) {
		super.initConfig(authTokenConfig);// 必需调用父类的initConfig方法,或者重写里面所定义的cookieStore路径
	}

	public AuthToken parse(String uri, AuthTokenConfig config) {
		HttpGet request = initRequest(uri);
		//TODO System.out.println(httpClientContext.getUserToken(User.class)); 有待使用,类似session
		return execute(request);
	}
	
	public HttpGet initRequest(String uri){
		return new HttpGet(uri);
	}

	/**
	 * 执行请求获取响应内容
	 * 
	 * @param request
	 *            请求对象
	 * @return 响应内容
	 */
	public AuthToken execute(HttpGet request) {
		
		super.httpClient = HttpClients.custom()
				.setConnectionManager(PoolingHttpClientConnection.getInstalce())
				.addInterceptorLast(new AuthTokenRequestInterceptor(super.config))
				.setDefaultRequestConfig(cookieRequestConfig(CookieSpecs.NETSCAPE))
				.setDefaultCookieStore(readCookieStoreDisk(AuthTokenConst.BASE_COOKIES_VALUES))
				.build();
		try {
			return super.httpClient.execute(request,new AuthTokenResponseHandle(this), super.httpClientContext);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
